<template>
	<view class="container">
		<!-- 搜索栏 -->
		<view class="search-box">
			<view class="search-input">
				<text class="iconfont icon-search"></text>
				<input type="text" v-model="searchQuery" placeholder="搜索商品" confirm-type="search" @confirm="handleSearch" />
			</view>
		</view>
		
		<!-- 轮播图 -->
		<swiper class="banner-swiper" circular indicator-dots autoplay :interval="3000" :duration="500" indicator-active-color="#409EFF">
			<swiper-item v-for="(item, index) in banners" :key="index">
				<image :src="getImgUrl(item.image)" mode="aspectFill" class="banner-image" @click="handleBannerClick(item)"></image>
			</swiper-item>
		</swiper>
		
		<!-- 分类导航 -->
		<view class="category-section">
			<view class="section-title">
				<text>商品分类</text>
				<view class="refresh-btn" @click="refreshCategories">
					<text class="refresh-text">刷新</text>
				</view>
			</view>
			<view class="category-grid">
				<view class="category-item" v-for="(item, index) in categories.slice(0, 8)" :key="index" @click="handleCategoryClick(item)">
					<view class="category-tag" :class="'category-tag-' + (index % 5)">
						{{ item.name }}
					</view>
				</view>
			</view>
		</view>
		
		<!-- 商品列表 -->
		<view class="goods-section">
			<view class="section-title">
				<text>猜你喜欢</text>
				<view class="title-decoration"></view>
			</view>
			<view class="goods-list">
				<view class="goods-item" v-for="(item, index) in goodsList" :key="index" @click="goToDetail(item.id)">
					<image :src="getImgUrl(item.image && item.image.length > 0 ? item.image[0] : '')" mode="aspectFill" class="goods-image"></image>
					<view class="goods-info">
						<text class="goods-name">{{ item.name }}</text>
						<text class="goods-price">¥{{ item.price }}</text>
						<view class="goods-footer">
							<text class="goods-sales">销量: {{ item.salesVolume || 0 }}</text>
							<text class="goods-stock" v-if="item.stock">库存: {{ item.stock }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 加载更多 -->
		<view class="loading-more" v-if="loading">
			<text>正在加载...</text>
		</view>
		<view class="no-more" v-if="noMore">
			<text>没有更多商品了</text>
		</view>
	</view>
</template>

<script>
import http, { SERVER_BASE_URL } from '@/utils/request';

	export default {
		data() {
			return {
			searchQuery: '',
			banners: [],
			categories: [],
			goodsList: [],
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				status: 'ON_SALE'
			},
			loading: false,
			noMore: false
		};
		},
		onLoad() {
		// 初始化数据
		this.fetchBanners();
		this.fetchCategories();
		this.fetchGoodsList();
	},
	onPullDownRefresh() {
		// 下拉刷新
		this.refreshData();
	},
	onReachBottom() {
		// 上拉加载更多
		this.loadMoreGoods();
		},
		methods: {
		// 从服务器获取轮播图数据
		async fetchBanners() {
			this.useFallbackBanners();
			// try {
			// 	const res = await uni.request({
			// 		url: SERVER_BASE_URL + '/banner/list',
			// 		method: 'GET'
			// 	});
				
			// 	if (res.statusCode === 200 && res.data) {
			// 		if (Array.isArray(res.data)) {
			// 			this.banners = res.data;
			// 		} else if (res.data.data && Array.isArray(res.data.data)) {
			// 			this.banners = res.data.data;
			// 		} else {
			// 			console.error('获取轮播图数据格式错误', res.data);
			// 			this.useFallbackBanners();
			// 		}
			// 	} else {
			// 		console.error('获取轮播图失败，使用备用数据', res);
			// 		this.useFallbackBanners();
			// 	}
			// } catch (error) {
			// 	console.error('获取轮播图数据失败', error);
			// 	this.useFallbackBanners();
			// }
		},
		
		// 使用备用的轮播图数据
		useFallbackBanners() {
			this.banners = [
				{ image: '/uploads/static/carousel/1.png', link: '' },
				{ image: '/uploads/static/carousel/2.png', link: '' },
				{ image: '/uploads/static/carousel/3.png', link: '' },
				{ image: '/uploads/static/carousel/4.png', link: '' }
			];
		},
		
		// 从服务器获取分类数据
		async fetchCategories() {
			try {
				// 尝试先从服务器获取
				const res = await uni.request({
					url: SERVER_BASE_URL + '/category.json',
					method: 'GET'
				});
				
				if (res.statusCode === 200 && res.data) {
					this.initCategories(res.data);
				} else {
					// 如果服务器请求失败，使用本地静态数据
					console.error('获取分类数据失败，使用本地数据', res);
					// 使用导入的静态数据
					const staticCategoryData = [
						{
							"name": "特价泡面",
							"Tag": ["特价泡面","泡面"]
						},
						{
							"name": "特价零食",
							"Tag": ["特价零食","零食"]
						},
						{
							"name": "特价饮料",
							"Tag": ["特价饮料","饮料"]
						},
						{
							"name": "炸串小吃",
							"Tag": ["炸串小吃","炸串"]
						},
						{
							"name": "炒饭盖饭",
							"Tag": ["炒饭盖饭","炒饭","盖饭"]
						},
						{
							"name": "零食饮料",
							"Tag": ["零食","饮料"]
						},
						{
							"name": "生活用品",
							"Tag": ["生活用品"]
						}
					];
					this.initCategories(staticCategoryData);
				}
			} catch (error) {
				console.error('获取分类数据失败', error);
				uni.showToast({
					title: '获取分类数据失败',
					icon: 'none'
				});
				this.categories = [];
			}
		},
		
		// 初始化分类数据
		initCategories(categoryData) {
			try {
				// 确保categories已被正确获取
				if (!categoryData || !Array.isArray(categoryData)) {
					console.error('分类数据错误:', categoryData);
					this.categories = [];
					return;
				}
				// 随机打乱并限制数量
				this.categories = this.shuffleArray(categoryData).slice(0, 8);
			} catch (error) {
				console.error('初始化分类数据失败:', error);
				this.categories = [];
			}
		},
		
		// 随机打乱数组
		shuffleArray(array) {
			if (!array || !Array.isArray(array)) return [];
			const newArray = [...array];
			for (let i = newArray.length - 1; i > 0; i--) {
				const j = Math.floor(Math.random() * (i + 1));
				[newArray[i], newArray[j]] = [newArray[j], newArray[i]];
			}
			return newArray;
		},
		
		// 获取商品列表
		async fetchGoodsList() {
			if (this.loading || this.noMore) return;
			
			this.loading = true;
			try {
				const res = await http.get('/commodities/page', this.queryParams);
				const list = res.list || [];
				
				if (this.queryParams.pageNum === 1) {
					this.goodsList = list;
				} else {
					this.goodsList = [...this.goodsList, ...list];
				}
				
				// 判断是否还有更多数据
				if (res.total && this.goodsList.length >= res.total) {
					this.noMore = true;
				}
			} catch (error) {
				console.error('获取商品列表失败', error);
				uni.showToast({
					title: '获取商品列表失败',
					icon: 'none'
				});
			} finally {
				this.loading = false;
				uni.stopPullDownRefresh();
			}
		},
		
		// 加载更多商品
		loadMoreGoods() {
			if (this.loading || this.noMore) return;
			
			this.queryParams.pageNum++;
			this.fetchGoodsList();
		},
		
		// 刷新数据
		refreshData() {
			this.queryParams.pageNum = 1;
			this.noMore = false;
			this.fetchBanners();
			this.fetchCategories();
			this.fetchGoodsList();
		},
		
		// 处理搜索
		handleSearch() {
			if (!this.searchQuery.trim()) return;
			
			// 把搜索关键词存入本地存储
			uni.setStorageSync('searchKeyword', this.searchQuery);
			// 使用switchTab跳转到分类页面，因为它是tabBar页面
			uni.switchTab({
				url: '/pages/category/category'
			});
		},
		
		// 处理分类点击
		handleCategoryClick(category) {
			// 把分类标签存入本地存储
			if (category.Tag && category.Tag.length > 0) {
				uni.setStorageSync('categoryTag', category.Tag);
			}
			// 使用switchTab跳转到分类页面，因为它是tabBar页面
			uni.switchTab({
				url: '/pages/category/category'
			});
		},
		
		// 处理轮播图点击
		handleBannerClick(banner) {
			if (banner.link) {
				uni.navigateTo({
					url: banner.link
				});
			}
		},
		
		// 跳转到商品详情
		goToDetail(id) {
			uni.navigateTo({
				url: `/pages/detail/detail?id=${id}`
			});
		},
		
		// 处理图片URL
		getImgUrl(url) {
			if (!url) return '';
			
			// 确保有服务器地址前缀
			let fullUrl = url;
			
			if (url.startsWith('/uploads/') || url.startsWith('/static/')) {
				fullUrl = SERVER_BASE_URL + url;
			}
			
			return fullUrl;
		},
		
		// 刷新分类
		refreshCategories() {
			uni.showLoading({
				title: '刷新中...'
			});
			
			// 再次获取分类数据
			this.fetchCategories();
			
			setTimeout(() => {
				uni.hideLoading();
				uni.showToast({
					title: '刷新成功',
					icon: 'success',
					duration: 1500
				});
			}, 500);
		}
	}
};
</script>

<style>
.container {
	padding-bottom: 20rpx;
	background-color: #f5f5f5;
}

/* 搜索栏样式 */
.search-box {
	padding: 20rpx 30rpx;
	background-color: #ffffff;
}

.search-input {
	display: flex;
	align-items: center;
	height: 70rpx;
	padding: 0 30rpx;
	background-color: #f5f5f5;
	border-radius: 35rpx;
}

.icon-search {
	margin-right: 10rpx;
	font-size: 28rpx;
	color: #999;
}

.search-input input {
	flex: 1;
	height: 70rpx;
	font-size: 28rpx;
}

/* 轮播图样式 */
.banner-swiper {
	width: 100%;
	height: 300rpx;
}

.banner-image {
	width: 100%;
	height: 100%;
}

/* 分类导航样式 */
.category-section {
	margin: 20rpx 0;
	padding: 20rpx;
	background-color: #ffffff;
	border-radius: 12rpx;
}

.section-title {
	margin-bottom: 20rpx;
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	position: relative;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.title-decoration {
	position: absolute;
	bottom: -6rpx;
	left: 0;
	width: 60rpx;
	height: 6rpx;
	background: linear-gradient(90deg, #409EFF 0%, #67C23A 100%);
	border-radius: 3rpx;
}

.refresh-btn {
	padding: 8rpx 20rpx;
	border-radius: 30rpx;
	background-color: #f5f5f5;
	border: 1px solid #eee;
		display: flex;
		align-items: center;
}

.refresh-text {
	font-size: 24rpx;
	color: #666;
	font-weight: normal;
}

.category-grid {
	display: flex;
	flex-wrap: wrap;
	justify-content: space-between;
	}

.category-item {
	width: 48%;
	margin-bottom: 20rpx;
	background-color: #ffffff;
	border-radius: 12rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.category-tag {
	padding: 20rpx;
	font-size: 26rpx;
	border-radius: 10rpx;
	color: #ffffff;
	text-align: center;
	display: block;
	width: 100%;
	box-sizing: border-box;
}

.category-tag-0 {
	background-color: #409EFF;
}

.category-tag-1 {
	background-color: #67C23A;
}

.category-tag-2 {
	background-color: #E6A23C;
}

.category-tag-3 {
	background-color: #F56C6C;
}

.category-tag-4 {
	background-color: #909399;
}

/* 商品列表样式 */
.goods-section {
	margin: 20rpx 0;
	padding: 20rpx;
	background-color: #ffffff;
	border-radius: 12rpx;
}

.goods-list {
	display: flex;
	flex-wrap: wrap;
	justify-content: space-between;
}

.goods-item {
	width: 48%;
	margin-bottom: 20rpx;
	background-color: #ffffff;
	border-radius: 12rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

.goods-image {
	width: 100%;
	height: 300rpx;
}

.goods-info {
	padding: 16rpx;
}

.goods-name {
	display: block;
	font-size: 28rpx;
	color: #333;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.goods-price {
	display: block;
	font-size: 32rpx;
	color: #ff6700;
	font-weight: bold;
	margin: 10rpx 0;
}

.goods-footer {
		display: flex;
	justify-content: space-between;
	font-size: 22rpx;
	color: #999;
}

/* 加载更多样式 */
.loading-more, .no-more {
	padding: 20rpx 0;
	text-align: center;
	font-size: 24rpx;
	color: #999;
	}
</style>
